<script setup>
import { ref, onMounted } from 'vue'

const props = defineProps({
  width: {
    type: Number,
    default: 120
  },
  height: {
    type: Number,
    default: 40
  }
})

const code = ref('')
const canvas = ref(null)

// 生成随机验证码
const generateCode = () => {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = ''
  for (let i = 0; i < 4; i++) {
    result += chars[Math.floor(Math.random() * chars.length)]
  }
  code.value = result
  drawCode()
}

// 绘制验证码
const drawCode = () => {
  const ctx = canvas.value.getContext('2d')
  ctx.fillStyle = '#f0f2f5'
  ctx.fillRect(0, 0, props.width, props.height)
  
  // 绘制文字
  ctx.font = '24px Arial'
  ctx.fillStyle = '#333'
  ctx.textBaseline = 'middle'
  const chars = code.value.split('')
  chars.forEach((char, i) => {
    const x = (i + 1) * (props.width / (chars.length + 1))
    const y = props.height / 2
    const rotate = (Math.random() - 0.5) * 0.3
    ctx.save()
    ctx.translate(x, y)
    ctx.rotate(rotate)
    ctx.fillText(char, -8, 0)
    ctx.restore()
  })
  
  // 绘制干���线
  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = `rgba(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255},0.5)`
    ctx.beginPath()
    ctx.moveTo(Math.random() * props.width, Math.random() * props.height)
    ctx.lineTo(Math.random() * props.width, Math.random() * props.height)
    ctx.stroke()
  }
}

// 暴露验证方法给父组件
defineExpose({
  validate: (value) => value.toLowerCase() === code.value.toLowerCase(),
  refresh: generateCode
})

onMounted(() => {
  generateCode()
})
</script>

<template>
  <canvas 
    ref="canvas"
    :width="width"
    :height="height"
    @click="generateCode"
    style="cursor: pointer; vertical-align: middle;"
  ></canvas>
</template> 